package com.rongke.interceptor;

import com.rongke.redis.RedisClusterCache;
import com.rongke.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by bin on 2018/3/23.
 */
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private RedisClusterCache redisClusterCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String url = request.getRequestURI();
        String method =request.getMethod();
        String token = request.getHeader("x-client-token");
        if (StringUtil.isNotEmpty(token) || url.equals("/api/admin/loginPhoneadmin") || method.equals("OPTIONS") || url.equals("/api/admin/getAdminInfo") ) {
            return true;
        }

        Cookie[] cookies = request.getCookies();
        String value = "";
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("JSESSIONID")) {
                    value = cookie.getValue();
                    break;
                }
            }
        }
        if (StringUtil.isNotEmpty(value) && redisClusterCache.haveCache(value) == true) {
            return true;
        }else {
            String origin = request.getHeader("Origin");
            response.setHeader("Access-Control-Allow-Origin",origin);
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Headers", "content-type");
            ServletOutputStream out = response.getOutputStream();
            out.print("unlogin");//返回给前端页面的未登陆标识
            out.flush();
            out.close();
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception {

    }
}
